package JZ.JZ56;


import java.util.Scanner;

/**
 * @author corn
 * @create 2020-07-24-21:53
 */

/**
 * JZ56 删除链表中重复的结点
 * 1->2->3->3->4->4->5
 */
public class DeleteDuplication {
    public static void main(String[] args) {
        Solution sol = new Solution();
        ListNode pHead = new ListNode(1);
        ListNode code1 = new ListNode(2);
        pHead.next = code1;
        ListNode code2 = new ListNode(3);
        code1.next = code2;
        ListNode code3 = new ListNode(3);
        code2.next = code3;
        ListNode code4 = new ListNode(4);
        code3.next = code4;
        ListNode code5 = new ListNode(4);
        code4.next = code5;
        ListNode code6 = new ListNode(5);
        code5.next = code6;
        pHead = sol.deleteDuplication(pHead);
        while (pHead != null){
            System.out.println(pHead.val);
            pHead = pHead.next;
        }
    }

}
class Solution {
    public ListNode deleteDuplication(ListNode pHead){
        if(pHead == null || pHead.next == null){
            return pHead;
        }
        // 自己构建辅助头结点
        ListNode head = new ListNode(Integer.MIN_VALUE);
        head.next = pHead;
        ListNode pre = head;
        ListNode cur = head.next;
        while(cur!=null){
            if(cur.next != null && cur.next.val == cur.val){
                // 相同结点一直前进
                while(cur.next != null && cur.next.val == cur.val){
                    cur = cur.next;
                }
                // 退出循环时，cur 指向重复值，也需要删除，而 cur.next 指向第一个不重复的值
                // cur 继续前进
                cur = cur.next;
                // pre 连接新结点
                pre.next = cur;
            }else{
                pre = cur;
                cur = cur.next;
            }
        }
        return head.next;
    }
}
class ListNode{
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}